import QtQuick 1.1
import meegim 1.0

MyPage {
    id: rosterPage
    objectName: "rosterPage"

    property string selectedName: ""

    Connections {
        target: muc

        onInvitationMucReceived: {
            dlgInviteMUC.dlgShowHide()
        }
    }

    Connections {
        target: xmppClient
        onConnectingChanged: {
            if( xmppClient.stateConnect == XmppClient.Connecting ) {
                console.log( "QML: RosterPage: connestion ... called statConnection()" )
                statConnection()
            } else if ( xmppClient.stateConnect == XmppClient.Connected ) {
                statConnected()
                console.log("QML: RosterPage: connected ... called statConnected()")
            } else if ( xmppClient.stateConnect == XmppClient.Disconnect ) {
                statDisonnected()
                console.log("QML: RosterPage: disconnectd ... called statDisonnected()")
            }
        }

        onStatusChanged: {
            console.log( "QML: RosterPage: onStatusChanged:" + xmppClient.status )
            setStatusStatus( xmppClient.status, xmppClient.statusText )
        }

        onStatusTextChanged: {
            console.log( "QML: RosterPage: onStatusTextChanged:" + xmppClient.statusText )
            setStatusStatus( xmppClient.status, xmppClient.statusText )
        }

        onErrorHappened: {
            setStatusStatus( xmppClient.status, xmppClient.statusText )
        }

        onSubscriptionReceived: {
            console.log( "QML: RosterPage: ::onSubscriptionReceived: [" + bareJid + "]" )
            createInfoPanel( "", "Subscription received \n from "+bareJid, 5000, "lightblue" )
            dlgSubscribes.addBareJid( bareJid )
        }
    }

    function statConnection() {
        connectingRect.opacity = 0.4
    }

    function statConnected() {
        connectingRect.opacity = 0
    }

    function statDisonnected() {
        connectingRect.opacity = 0
    }


    function setStatusStatus( status, statText ) {
        var resSet = dlgMyStatus.setStatus( status, statText )
        if( !resSet ) {
            return;
        }
        //console.log("<***>setStatusStatus: [" + status + "] [" + statText + "]")
        //console.log("setStatusStatus: XmppClient.Online: [" + XmppClient.Online + "]")

        if( (status == XmppClient.Online) || (status == XmppClient.Chat) ) {
            toolBarButtonPresence.icon = "qrc:/qml/images/bar_presence_online.png"
            console.log( "toolBarButtonPresence.icon: " + toolBarButtonPresence.icon )
        } else if( (status == XmppClient.Away) || (status == XmppClient.XA) ) {
            toolBarButtonPresence.icon = "qrc:/qml/images/bar_presence_away.png"
        } else if(  status == XmppClient.DND ) {
            toolBarButtonPresence.icon = "qrc:/qml/images/bar_presence_busy.png"
        } else if(  status == XmppClient.Offline ) {
            toolBarButtonPresence.icon = "qrc:/qml/images/bar_presence_offline.png"
        }
    }

    Component.onCompleted: {
        /* блокировка ориентации */
        main.appOrientation = main.orPortrait

        setStatusStatus( xmppClient.status, xmppClient.statusText )

        if( main.invRoomJid != "" )
        {
            dlgInviteMUC.dlgShowHide()
        }
    }


    DialogQuery {
        id: dlgInviteMUC
        title: "Invitation"
        text: "Invitation to\n" + invRoomJid
        textButtonOk: qsTr("Accept")
        textButtonCancel: qsTr("Reject")
        inverseMouseArea: false
        onClickedOk: {
            if( invRoomJid != "" ) {
                //xmppClient.addMucRoster( invRoomJid, muc.subjectRoom ) //add muc to roster
                //muc.jidRoom = invRoomJid //enter to muc
                rosterPage.closePage( "qrc:/qml/MucLoginPage.qml" )
            }
            dlgShowHide()
            //invRoomJid = ""
            //invIniterJid = ""
        }
        onClickedCancel: {
            dlgShowHide()
            invRoomJid = ""
            invIniterJid = ""
        }
    }
    /*******************************************************************************/

    colorPage: "white"

    property int __selectedContactItemType: 0
    Component {
        id: componentRosterItem
        HorizontalGradient {
            id: wrapper
            clip: true
            width: listViewRoster.width
            height: 90
            //border.color: "blue"

            ListView.onAdd: ParallelAnimation {
                NumberAnimation {
                    target: wrapper
                    property: "opacity"
                    from: 0; to: 1
                    duration: 600
                    easing.type: Easing.InOutQuad
                }
                NumberAnimation {
                    target: wrapper;
                    property: "scale";
                    duration: 600;
                    from: 0.01; to: 1
                    easing.type: Easing.InOutQuad
                }
            }

            ListView.onRemove: ParallelAnimation {
                NumberAnimation {
                    target: wrapper
                    property: "opacity"
                    from: 1; to: 0
                    duration: 600
                    easing.type: Easing.InOutQuad
                }
                NumberAnimation {
                    target: wrapper;
                    property: "scale";
                    duration: 600;
                    from: 1; to: 0.01
                    easing.type: Easing.InOutQuad
                }
            }

            /*ListView.onFlickingChanged: {
                console.log( index + ") =>" + pos.x + " " + pos.y )
            }*/

            Image {
                id: imgPresence
                //source: contactPicStatus
                source: contactItemType == 0 ? contactPicStatus : "qrc:/qml/images/muc.png"
                anchors.verticalCenter: parent.verticalCenter
                anchors.left: parent.left
                anchors.leftMargin: 7

                Text {
                    id: txtUnreadMsg
                    text: contactUnreadMsg
                    font.pixelSize: 22
                    anchors.centerIn: parent
                    visible: contactUnreadMsg != 0
                    z: 1
                }

                Image {
                    id: imgNewMsg
                    source: "qrc:/qml/images/message.png"
                    anchors.centerIn: parent
                    smooth: true
                    scale: 0.8
                    visible: contactUnreadMsg != 0
                    SequentialAnimation {
                        running: contactUnreadMsg != 0
                        loops: Animation.Infinite
                        NumberAnimation {
                            target: imgNewMsg
                            property: "opacity"
                            from: 1; to: 0.4
                            duration: 1300
                            easing.type: Easing.InOutQuad
                        }
                        NumberAnimation {
                            target: imgNewMsg
                            property: "opacity"
                            from: 0.4; to: 1
                            duration: 1300
                            easing.type: Easing.InOutQuad
                        }
                    }
                } //imgNewMsg

            } //imgPresence

            HorizontalGradient {
                z: 1
                id: wrapperTxtJid
                anchors.left: imgPresence.right
                anchors.leftMargin: 5
                anchors.top: parent.top
                anchors.topMargin: 1
                height: parent.height/2 - 2
                width: contactItemType == 0 ? parent.width - (imgPresence.width + imgPresence.anchors.leftMargin) - (imgAvatar.width + imgAvatar.anchors.rightMargin) - 5 : parent.width - (imgPresence.width + imgPresence.anchors.leftMargin)
                gradient: Gradient {
                    GradientStop { color: "transparent"; position: 0 }
                    GradientStop { color: "transparent"; position: 0.8 }
                    GradientStop { color: "white"; position: 0.96 }
                    GradientStop { color: "white"; position: 1 }
                }
            }
            Item {
                anchors.verticalCenter: wrapperTxtJid.verticalCenter
                anchors.left: wrapperTxtJid.left
                height: wrapperTxtJid.height
                width: wrapperTxtJid.width
                clip: true
                Text {
                    id: txtJid
                    clip: true
                    //text: (contactName === "" ? contactJid : contactName) + (contactResource !== "" ? "/" + contactResource : "")
                    text: (contactName === "" ? contactJid : contactName)
                    font.pixelSize: 28
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: parent.left
                }
            }

            HorizontalGradient {
                z: 1
                id: wrapperTxtStatus
                anchors.left: imgPresence.right
                anchors.leftMargin: 5
                anchors.top: wrapperTxtJid.bottom
                anchors.topMargin: 1
                height: parent.height/2 - 2
                width: contactItemType == 0 ? parent.width - (imgPresence.width + imgPresence.anchors.leftMargin) - (imgAvatar.width + imgAvatar.anchors.rightMargin) - 5 : parent.width - (imgPresence.width + imgPresence.anchors.leftMargin)
                gradient: Gradient {
                    GradientStop { color: "transparent"; position: 0 }
                    GradientStop { color: "transparent"; position: 0.8 }
                    GradientStop { color: "white"; position: 0.96 }
                    GradientStop { color: "white"; position: 1 }
                }
            }
            Item {
                anchors.verticalCenter: wrapperTxtStatus.verticalCenter
                anchors.left: wrapperTxtStatus.left
                height: wrapperTxtStatus.height
                width: wrapperTxtStatus.width
                clip: true
                Text {
                    id: txtStatus
                    text: contactTextStatus
                    font.pixelSize: 22
                    color: "gray"
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: parent.left
                }
            }

            Image {
                id: imgAvatar
                smooth: true
                height: 80
                width: 80
                anchors.right: parent.right
                anchors.rightMargin: 5
                anchors.verticalCenter: parent.verticalCenter
                source: contactPicAvatar === "" ? "qrc:/qml/images/avatar.png" : contactPicAvatar
                Image {
                    anchors.centerIn: parent
                    source: "qrc:/qml/images/meego_frame_80.png"
                }
                visible: contactItemType == 0 ? true : false
            }

            gradient: Gradient {
                GradientStop{ id: posGr1; color: "white"; position: 0 }
                GradientStop{ id: posGr5; color: "white"; position: 0 }
                GradientStop{ id: posGr2; color: "white"; position: 0 }
                GradientStop{ id: posGr3; color: "white"; position: 0 }
                GradientStop{ id: posGr4; color: "white"; position: 1 }
            }


            states: State {
                name: "Current"
                when: (wrapper.ListView.isCurrentItem && (xmppClient.chatJid != "") )
                PropertyChanges { target: posGr1; position: 0 }
                PropertyChanges { target: posGr1; color: "white" }
                PropertyChanges { target: posGr5; position: 0.04 }
                PropertyChanges { target: posGr5; color: "lightblue" }
                PropertyChanges { target: posGr2; position: 0.3 }
                PropertyChanges { target: posGr2; color: "lightblue" }
                PropertyChanges { target: posGr3; position: 0.7 }
                PropertyChanges { target: imgPresence; anchors.leftMargin: 15 }
            }

            transitions: Transition {
                NumberAnimation { properties: "position"; duration: 300 }
                NumberAnimation { properties: "anchors.leftMargin"; duration: 300 }
            }

            MouseArea {
                id: mouseAreaItem;
                anchors.fill: parent

                onClicked: {
                    wrapper.ListView.view.currentIndex = index
                    xmppClient.chatJid = contactJid
                    selectedName = contactName
                    __selectedContactItemType = contactItemType
                }

                onDoubleClicked: {
                    wrapper.ListView.view.currentIndex = index
                    xmppClient.chatJid = contactJid
                    //xmppClient.openChat( contactJid ) //команда в С++ -> открыть чат //это уже делается в окне сообщений
                    __selectedContactItemType = contactItemType
                    if( contactItemType == 0 ) {
                        rosterPage.closePage( "qrc:/qml/MessagesPage.qml" )
                    } else {
                        rosterPage.closePage( "qrc:/qml/MucPage.qml" )
                    }
                }

                onPressAndHold: {
                    wrapper.ListView.view.currentIndex = index
                    xmppClient.chatJid = contactJid
                    selectedName = contactName
                }
            }
        } //Rectangle
    }



    ListView {
        id: listViewRoster
        anchors.top: parent.top
        anchors.bottom: toolBar.top
        anchors.left: parent.left
        anchors.right: parent.right
        clip: true
        delegate: componentRosterItem
        model: xmppClient.roster
        /*section {
            property: "contactGroup"
            criteria: ViewSection.FullString
            delegate: Rectangle {
                color: "lightgray"
                width: parent.width
                height: 40
                Text {
                    //anchors.verticalCenter: parent.verticalCenter
                    anchors.centerIn: parent
                    text: section
                    font.pixelSize: 28
                }
            }
        }*/
    }


    /********************************( Диалог переключения статуса )************************************/

    DialogMyStatus {
        id: dlgMyStatus
        onMyStatusChange: {
            /* TODO: здесь нужна проверка на аккаунт */
            if( settings.accounts.count() == 0 ) {
                console.log( ">>> need to create an account" )
                dlgInfo.title = "Error"
                dlgInfo.text = "Need to create an account"
                dlgInfo.show()
                return
            } else if( ! main._existDefaultAccount ) {
                console.log(">>> need to check by default")
                dlgInfo.title = "Error"
                dlgInfo.text = "Choose account by default"
                dlgInfo.show()
                return
            }

            toolBarButtonPresence.icon = "qrc:/qml/images/bar_presence_unknown.png"

            xmppClient.keepAlive = settings.keepAliveInterval
            xmppClient.reconnectOnError = settings.reconnectWhenError
            xmppClient.setMyPresence( dlgMyStatus.myStatusSet, dlgMyStatus.myTextStatus )

            settings.saveStatusText( dlgMyStatus.myTextStatus )
        }
    }

    /*******/

    DialogInfo {
        id: dlgInfo
        fontTextSize: 26
    }

    DialogQuery {
        id: dlgQueryRemove
        onClickedOk: {
            xmppClient.removeContact( xmppClient.chatJid )
        }
        title: qsTr("Remove contact")
        /*onClickedCancel: {
            dlgQueryRemove.hide()
        }*/
    }

    DialogEdit {
        id: dlgRenameContact
        title: qsTr("Rename contact")
        onClickedOk: {
            if( dlgRenameContact.textEdit != "" ) {
                xmppClient.renameContact( xmppClient.chatJid, dlgRenameContact.textEdit )
            }
        }
    }

    DialogSubscribes {
        id: dlgSubscribes
    }

    /*******/

    DialogOptionsRoster {
        id: dlgRosterOptions
        isOnline: xmppClient.stateConnect == XmppClient.Online ? true : false
        onItemClicked:
        {
            if( dlgRosterOptions.itemSelected == "accounts" )
            {
                rosterPage.closePage( "qrc:/qml/AccountsPage.qml" )
            }
            else if( dlgRosterOptions.itemSelected == "contactadd" )
            {
                if( xmppClient.stateConnect == XmppClient.Online ) {
                    rosterPage.closePage( "qrc:/qml/AddContactPage.qml" )
                }
            }
            else if( ( dlgRosterOptions.itemSelected == "contactremove" ) && ( xmppClient.stateConnect == XmppClient.Online ) && (xmppClient.chatJid != "") )
            {
                dlgQueryRemove.text = qsTr("Remove") + " " + xmppClient.chatJid + " ?"
                dlgQueryRemove.dlgShowHide()
            }
            else if( ( dlgRosterOptions.itemSelected == "contactedit" ) && ( xmppClient.stateConnect == XmppClient.Online ) && (xmppClient.chatJid != "") )
            {
                dlgRenameContact.textEdit = selectedName
                dlgRenameContact.text = qsTr("Rename") + " " + xmppClient.chatJid
                dlgRenameContact.show()
            }
            else if( dlgRosterOptions.itemSelected == "quit" )
            {
                Qt.quit()
            }
            else if( (dlgRosterOptions.itemSelected == "vcard") && ( xmppClient.chatJid != "" ) )
            {
                rosterPage.closePage( "qrc:/qml/VCardPage.qml" )
            }
            else if( dlgRosterOptions.itemSelected == "myvcard" )
            {
                if( xmppClient.stateConnect == XmppClient.Online )
                {
                    main.requestMyVCard = true
                    rosterPage.closePage( "qrc:/qml/VCardPage.qml" )
                }
            }
            else if( dlgRosterOptions.itemSelected == "about" )
            {
                rosterPage.closePage( "qrc:/qml/AboutPage.qml" )
            }
            else if( dlgRosterOptions.itemSelected == "offlinejid" )
            {
                xmppClient.showOffline = !xmppClient.showOffline
            }
            else if( dlgRosterOptions.itemSelected == "settings" )
            {
                rosterPage.closePage( "qrc:/qml/SettingsPage.qml" )
            }
            else if( dlgRosterOptions.itemSelected == "contactsubscribe" )
            {
                dlgInfo.text = qsTr("Sent authorization to ")+xmppClient.chatJid
                var r = xmppClient.subscribe( xmppClient.chatJid )
                if( r == true ) { dlgInfo.show(); }
            }
            else if( dlgRosterOptions.itemSelected == "contactunsubscribe" )
            {
                //dlgInfo.text = "Authorization has been removed"
                var r = xmppClient.unsubscribe( xmppClient.chatJid )
                //if( r == true ) { dlgInfo.show(); }
            }
            else if( dlgRosterOptions.itemSelected == "subscribes" )
            {
                if( dlgRosterOptions.state == "visible" ) {
                    dlgRosterOptions.dlgShowHide()
                }
                dlgSubscribes.dlgShowHide();
            }
            else if( dlgRosterOptions.itemSelected == "enterroom" )
            {
                if( xmppClient.stateConnect == XmppClient.Online ) {
                    rosterPage.closePage( "qrc:/qml/MucLoginPage.qml" )
                }
            }
        }
    }

    /********************************( Toolbar )************************************/

    ToolBar {
        id: toolBar
        ToolButton {
            id: toolBarButtonPresence
            icon: "qrc:/qml/images/bar_presence_offline.png"
            anchors.left: parent.left
            anchors.leftMargin: (0.5*(parent.width/4) - 0.5*toolBarButtonPresence.width)
            onClicked: {
                if( dlgRosterOptions.state == "visible" ) {
                    dlgRosterOptions.dlgShowHide()
                }
                dlgMyStatus.dlgShowHide()
            }
            pauseAnim: 500
        }
        ToolButton {
            id: toolBarButtonOptions
            icon: "qrc:/qml/images/bar_options.png"
            anchors.left: parent.left
            anchors.leftMargin: (1.5*(parent.width/4) - 0.5*toolBarButtonOptions.width)
            onClicked: {
                if( dlgMyStatus.state == "visible" ) {
                    dlgMyStatus.dlgShowHide()
                }
                dlgRosterOptions.dlgShowHide()
            }
            pauseAnim: 600
        }
        ToolButton {
            id: toolBarButtonChats
            icon: "qrc:/qml/images/bar_open_chats.png"
            anchors.left: parent.left
            anchors.leftMargin: (2.5*(parent.width/4) - 0.5*toolBarButtonChats.width)
            onClicked: {
                rosterPage.closePage( "qrc:/qml/ChatsPage.qml" )
            }
            pauseAnim: 700
        }
        ToolButton {
            id: toolBarButtonDialog
            icon: "qrc:/qml/images/bar_messages.png"
            anchors.left: parent.left
            anchors.leftMargin: (3.5*(parent.width/4) - 0.5*toolBarButtonDialog.width)
            onClicked: {
                if( xmppClient.chatJid != "" ) {
                    //rosterPage.closePage( "qrc:/qml/MessagesPage.qml" ) //TODO: разделение на muc и chat.
                    if( __selectedContactItemType == 0 ) {
                        rosterPage.closePage( "qrc:/qml/MessagesPage.qml" )
                    } else {
                        rosterPage.closePage( "qrc:/qml/MucPage.qml" )
                    }
                }
                //main.createInfoPanel( "", "xxx --- xxx", 4000, "grey" )
            }
            pauseAnim: 800
        }
    }
    /*********************************************************************/


    /*********************************************************************/

    Rectangle {
        id: connectingRect
        z: 3
        anchors.top: parent.top
        anchors.bottom: toolBar.top
        anchors.left: parent.left
        anchors.right: parent.right
        color: "black"
        //opacity: main.connectionState == main.conConnecting ? 0.4 : 0
        opacity: xmppClient.stateConnect == XmppClient.Connecting ? 0.4 : 0
        Behavior on opacity { NumberAnimation { duration: 400 } }
    }

}
